# -*- coding: UTF-8 -*-
"""
HaaS506 RTU Temperature Sensor Demo
Function: RS485 Modbus temperature and humidity sensor data collection
Author: HaaS506 Development Team
Version: v1.0.0
Hardware: HaaS506-HD1_V4/V5 + Air780EP + RS485 Temperature Sensor

This demo shows how to read temperature and humidity data from RS485 Modbus sensor.
Sensor specifications: Address 0x0B, Function 0x04, registers for humidity and temperature.
"""

import utime as time
from driver import GPIO, UART
import temperature_sensor

# ====== Configuration ======
COLLECTION_INTERVAL = 5  # Data collection interval (seconds)
REPORT_INTERVAL = 30  # Data report interval (seconds)

# Global variables
sensor_data = {
    "temperature": 0.0,
    "humidity": 0.0,
}

# Hardware objects
status_led = None


def init_hardware():
    """Initialize hardware components"""
    print("Initializing hardware...")

    # Initialize status LED
    global status_led
    status_led = GPIO()
    status_led.open("status_led")
    print("LED initialized")

    # Initialize temperature sensor
    temperature_sensor.init()
    print("Temperature sensor initialized")

    print("Hardware initialization completed")


def led_blink():
    """Simple LED blink indication"""
    if status_led:
        status_led.write(1)
        time.sleep(0.1)
        status_led.write(0)


def led_status_indication(status_type, success=None):
    """LED status indication for different system states"""
    if not status_led:
        return

    try:
        if status_type == "system_start":
            # System startup - 5 quick blinks
            print("LED: System startup indication")
            for i in range(5):
                status_led.write(1)
                time.sleep(0.1)
                status_led.write(0)
                time.sleep(0.1)

        elif status_type == "sensor_test":
            # Sensor testing - 2 long blinks
            print("LED: Sensor testing indication")
            for i in range(2):
                status_led.write(1)
                time.sleep(0.5)
                status_led.write(0)
                time.sleep(0.3)

        elif status_type == "sensor_result":
            if success:
                # Sensor success - 3 quick blinks
                print("LED: Sensor communication SUCCESS")
                for i in range(3):
                    status_led.write(1)
                    time.sleep(0.2)
                    status_led.write(0)
                    time.sleep(0.2)
            else:
                # Sensor failed - 1 long blink
                print("LED: Sensor communication FAILED")
                status_led.write(1)
                time.sleep(1.0)
                status_led.write(0)

        elif status_type == "heartbeat":
            # System heartbeat - single short blink
            status_led.write(1)
            time.sleep(0.05)
            status_led.write(0)

        elif status_type == "error":
            # Error indication - rapid blinking
            print("LED: Error indication")
            for i in range(6):
                status_led.write(1)
                time.sleep(0.1)
                status_led.write(0)
                time.sleep(0.1)

    except Exception as e:
        print("LED indication error:", e)


def collect_sensor_data():
    """Collect temperature and humidity data"""
    global sensor_data

    # LED indication for sensor testing
    led_status_indication("sensor_test")

    # Read temperature and humidity
    humidity, temperature = temperature_sensor.read_temperature_humidity()

    if humidity is not None and temperature is not None:
        sensor_data["humidity"] = humidity
        sensor_data["temperature"] = temperature
        led_status_indication("sensor_result", success=True)
        return True
    else:
        led_status_indication("sensor_result", success=False)
        return False


def print_sensor_data():
    """Print collected sensor data"""
    print("Sensor Data:")
    print("  Temperature: {:.1f} °C".format(sensor_data["temperature"]))
    print("  Humidity: {:.1f} %RH".format(sensor_data["humidity"]))


def main():
    """Main program entry"""
    print("=" * 60)
    print("HaaS506 RTU Temperature Sensor Demo")
    print("Hardware: HaaS506-HD1_V4/V5 + Air780EP")
    print("Sensor: RS485 Modbus Temperature & Humidity Sensor")
    print("Version: v1.0.0 | Date: 2024-12")
    print("=" * 60)

    try:
        # 1. Initialize hardware
        init_hardware()

        # 2. LED startup indication
        led_status_indication("system_start")

        # 3. Start main loop
        print("Program running, collecting sensor data...")
        print("Collection interval: {} seconds".format(COLLECTION_INTERVAL))
        print("Report interval: {} seconds".format(REPORT_INTERVAL))
        print("Press Ctrl+C to stop")

        last_report_time = 0
        loop_count = 0

        while True:
            loop_count += 1
            current_time = time.time()

            print("\n--- Loop {} ---".format(loop_count))

            # LED heartbeat indication
            led_status_indication("heartbeat")

            # Collect sensor data
            success = collect_sensor_data()

            if success:
                print_sensor_data()
            else:
                print("Failed to read sensor data")

            # LED blink indication
            led_blink()

            # Print detailed report periodically
            if current_time - last_report_time >= REPORT_INTERVAL:
                print("\n" + "=" * 25)
                print("     Data Report")
                print("=" * 25)
                if success:
                    print("Temperature: {:.1f} °C".format(sensor_data["temperature"]))
                    print("Humidity: {:.1f} %RH".format(sensor_data["humidity"]))
                else:
                    print("No valid sensor data")
                print("=" * 25)
                last_report_time = current_time

            # Wait before next collection
            time.sleep(COLLECTION_INTERVAL)

    except KeyboardInterrupt:
        print("\nProgram interrupted by user")
    except Exception as e:
        print("Program runtime error:", e)
        led_status_indication("error")
    finally:
        # Clean up resources
        print("Cleaning up resources...")
        temperature_sensor.cleanup()
        print("Program ended")


if __name__ == "__main__":
    main()
